/**
 * 订单管理-订单审核
 * 
 * @author mouwanming
 */
var voucherOConfirmingMask = new Ext.LoadMask(Ext.getBody(), {
			msg : "正在提交,请稍后..."
		});
var queryVoucherOrderCheckSearch = function() {
	var queryVoucherOrdersConfirmingFieldSet = new Ext.form.FieldSet({
		id : 'queryVoucherOrdersConfirmingFieldSet',
		title : '查询条件',
		collapsible : true,// 可折叠
		buttonAlign : 'center',
		keys : [{
					key : 13, // 13代表回车
					fn : queryVoucherOrdersConfirming,
					scope : this
				}],
		items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											name : 'id',
											anchor : '100%',
											fieldLabel : '订单编号'
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											id : "voucherOrderConfirming_Code",
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '抵用券编号',
											name : "voucherCode"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											id : 'voucherOrderConfirming_orderStatusMultiCmb',
											xtype : 'dataDictionaryMultiCmb',
											anchor : '100%',
											fieldLabel : "订单状态",
											editable : false,
											autoLoad : false,
											hiddenValueId : 'voucherOrderManager_orderStatus',
											dictionaryType : PmsUtil.voucher_order_status
										}]
							},{
								id : 'voucherOrderManager_orderStatus',
								xtype : 'hidden',
								name : 'orderStatusIds'
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'dataDictionaryCmb',
											anchor : '100%',
											fieldLabel : "支付方式",
											editable : false,
											autoLoad : false,
											existall : true,
											defaultFirstRow : 1,
											hiddenName : 'payWays',
											dictionaryType : PmsUtil.orders_pay_type

										}]
							}]
				}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									layout : 'column',
									border : false,
									items : [{
												text : '查询',
												xtype : 'button',
												width : 70,
												handler : function() {
													queryVoucherOrdersConfirming();
												},
												style : {
													marginLeft : "450px",
													marginRight : "10px"
												}
											}, {
												text : '重置',
												xtype : 'button',
												width : 70,
												handler : function() {
													queryVoucherOrderCheckForm
															.getForm().reset();
													Ext
													.getCmp("voucherOrderConfirming_orderStatusMultiCmb")
													.reset();
												}
											
											}]
							}]
				}]
	});
	fieldSetListeners(['queryVoucherOrdersConfirmingFieldSet', 'queryVoucherOrderCheckForm',
					'voucherOrderManagerGrid'], [0.16, 0.84]);

	var queryVoucherOrderCheckForm = new Ext.form.FormPanel({
				id : 'queryVoucherOrderCheckForm',
				anchor : '100% 16%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryVoucherOrdersConfirmingFieldSet]
			});
	return queryVoucherOrderCheckForm;
};

/**
 * grids
 */

var voucherOrderConfirmingManagerGrid = function() {
	var voucherOrderManagerSm = new Ext.grid.CheckboxSelectionModel({
				checkOnly : true,
				renderer : function(v, p, record) {
					var voucherOrderStatus = record.get('orderStatus');
					if (voucherOrderStatus == PmsUtil.ORDER_STATUS_CONFRIM) {
						return '<div class="x-grid3-row-checker">&#160;</div>';
					} else {
						return '';
					}
				},
				listeners : {
					beforerowselect : function(SelectionModel, rowIndex,
							keepExisting, record) {
						var voucherOrderStatus = record.get('orderStatus');
						if (voucherOrderStatus == PmsUtil.ORDER_STATUS_CONFRIM) {
							return true;
						} else {
							return false;
						}
					}
				}

			});// 创建选择模式对象
	// 定义表的每列（对应表头信息）
	var voucherOrderManagerCm = new Ext.grid.ColumnModel([voucherOrderManagerSm, {
				dataIndex : "id",
				header : "订单编号",
				sortable : false,
				width : 60
			}, {
				dataIndex : "voucherCode",
				header : "抵用券编号",
				sortable : false,
				width : 160,
				renderer : function(value, cellmeta, record, rowIndex,
						columnIndex, store) {
					var returnValue = "";
					var orderId = record.data.id;
					if (value) {
						returnValue = '<a href ="#" onClick="lookVoucheOrderDetail(\''
								+ orderId + '\')">' + value + '</a>';
					}
					return returnValue;
				}
			}, {
				dataIndex : "userId",
				header : "用户编号",
				sortable : false,
				width : 70
			}, {
				dataIndex : "userName",
				header : "用户姓名",
				sortable : false,
				width : 60
			},{
				dataIndex : "voucherPaymentId",
				header : "支付流水ID",
				sortable : false,
				width : 80
			}, {
				dataIndex : "payDate",
				header : "支付时间",
				sortable : false,
				width : 130
			}, {
				dataIndex : "orderStatus",
				header : "订单状态",
				sortable : false,
				width : 60,
				renderer : function(value) {
					return '<font color=\"#FF0000\" >' + PmsUtil.VoucherOrderStatus(value) + '</font>';
				}
			}, {
				dataIndex : "payWays",
				header : "支付方式",
				sortable : false,
				width : 60,
				renderer : function(value) {
					return PmsUtil.PayType(value);

				}
			}, {
				dataIndex : "consignee",
				header : "收货人",
				sortable : false,
				width : 60
			},  {
				dataIndex : "voucherNumber",
				header : "商品数量",
				sortable : false,
				width : 70
			}, {
				dataIndex : "totalAmount",
				header : "订单总金额",
				sortable : false,
				width : 70,
				renderer : function(val) {
					return PmsUtil.Price(val);
				}
			}, {
				dataIndex : "payAmount",
				header : "实际支付金额",
				sortable : false,
				width : 90,
				renderer : function(val) {
					return PmsUtil.Price(val);
				}
			},{
				dataIndex : "consignPhone",
				header : "收货人电话",
				sortable : false,
				width : 100
			}, {
				dataIndex : "consignAddress",
				header : "收货人地址",
				sortable : false,
				width : 150,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="收货人地址:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "remark",
				header : "备注",
				sortable : false,
				width : 100,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="备注:" ext:qtip="' + value + '"';
						return value;
					}
				}
			},{
				dataIndex : "deliveryPicture",
				header : "确认发货图片",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.ShowPicture(value);

				}
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : false,
				width : 130
			}, {
				dataIndex : "createdName",
				header : "创建人",
				sortable : false,
				width : 60
			}, {
				header : "管理",
				width : 300,
				dataIndex : "id",
				renderer : function(j, i, g, m, h) {
					var orderId = g.data.id;
					
					var orderStatus = g.data.orderStatus;
					var payWays = g.data.payWays;
					var k = "";
					if (orderStatus == 1 && isGranted("voucherOrderConfirming_订单发货")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="insertVoucherOrderPicture('
								+ orderId
								+ ','
								+ "2"
								+ ','
								+ "'已发货'"
								+ ')\">订单发货</a>';
					}
					if (orderStatus == 2 && isGranted("voucherOrderConfirming_订单完成")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateVoucherOrderStatusOne('
								+ orderId
								+ ','
								+ "3"
								+ ','
								+ "'已完成'"
								+ ')\">订单完成</a>';
					}
					if ((orderStatus == 1 || orderStatus == 2)
							&& isGranted("voucherOrderConfirming_修改订单")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updCheckVoucherOrder('
								+ orderId + ')\">修改订单</a>';
					}
					if ((orderStatus == 1 || orderStatus == 2 || orderStatus == 0 || orderStatus == 3 ) && isGranted("voucherOrderConfirming_订单详情")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="lookVoucheOrderDetail('
								+ orderId + ')\">订单详情</a>';
					}
					if (orderStatus == 2 && isGranted("voucherOrderConfirming_订单打印")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="printOrder('
								+ orderId + ')\">订单打印</a>';
					}

					return k;
				}
			}]);

	// 定义分析器
	var voucherOrderManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
								name : "id"
							}, {
								name : "voucherCode"
							}, {
								name : "userId"
							}, {
								name : "userName"
							}, {
								name : "voucherPaymentId"
							}, {
								name : "orderStatus"
							}, {
								name : "payDate"
							}, {
								name : "payWays"
							},{
								name : "totalAmount"
							}, {
								name : "voucherNumber"
							}, {
								name : "payAmount"
							}, {
								name : "couponFee"
							}, {
								name : "couponSource"
							}, {
								name : "consignee"
							}, {
								name : "consignPhone"
							}, {
								name : "consignAddress"
							}, {
								name : "remark"
							}, {
								name : "createdDate"
							}, {
								name : "createdName"
							}, {
								name : "updatedDate"
							}, {
								name : "updatedName"
							}, {
								name : "logisticNo"
							}, {
								name : "deliveryPicture"
				}]
			});

	// 取数据store
	var voucherOrderViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath + "/voucherManager/selectVoucherOrders"
						}),
				remoteSort : true,
				baseParams : {
					start : 0,
					limit : 25,
					orderParam : 'id'
				},
				listeners : {
					beforeload : {						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryVoucherOrderCheckForm')
											.getForm().getValues());
						}
					}
				},
				reader : voucherOrderManagerReader
			});

	var voucherOrderConfirmingTb = new Ext.Toolbar({// 定义grid的toolbar
		height : 25,
		items : []
	});
	voucherOrderConfirmingTb.add(new Ext.scm.Button({
				text : "批量完成",
				width : 80,
				pressed : true,
				hsValue : 'voucherOrderConfirming_批量确认',
				iconCls : "btn-edit",
				listeners : {
					"click" : function() {
						batchOrderUpdateStatus(3, '已确认');
					}
				}
			}));
	voucherOrderConfirmingTb.add(new Ext.Toolbar.Spacer());
	voucherOrderConfirmingTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				hsValue : 'voucherOrderConfirming_刷新',
				pressed : true,
				handler : function() {
					queryVoucherOrdersConfirming();
				}
			}));
	var voucherOrderConfirmingManagerGrid = new Ext.grid.GridPanel({
				id : 'voucherOrderConfirmingManagerGrid',
				store : voucherOrderViewStore,
				cm : voucherOrderManagerCm,
				sm : voucherOrderManagerSm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 84%',
				frame : true,
				tbar : voucherOrderConfirmingTb,
				bbar : new PG.PagingBar({
							id : 'voucherOrderConfirmingGridPage',
							store : voucherOrderViewStore
						})
			});
	return voucherOrderConfirmingManagerGrid;
};

// 查询
function queryVoucherOrdersConfirming() {
	PmsUtil.StringTrim("voucherOrderConfirming_Code");
	if (Ext.getCmp('queryVoucherOrderCheckForm').getForm().isValid()) {
		var grid = Ext.getCmp('voucherOrderConfirmingManagerGrid');
		var store = grid.store;
		var pagesize = Ext.getCmp('voucherOrderConfirmingGridPage').pageSize;
		store.load({
					params : {
						start : 0,
						limit : pagesize,
						"VoucherOrderStatusArray" : '0,1,2,3'
					}
				});
	}
}

// 修改
function updCheckVoucherOrder(orderId) {
	Ext.Loader.load([__ctxPath + '/js/voucher/voucherOrderForm.js'], function() {
				updateVoucherOrderWin(orderId, 'voucherOrderConfirmingManagerGrid').show();
			});
}

/**
 * 查询订单详情
 * 
 * @param {}
 *            id
 */
function lookVoucheOrderDetail(id) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.VOUCHER_ORDER_MESSAGE_DETAIL);
	var createNewTab = new CreatNewTab(PmsUtil.VOUCHER_ORDER_MESSAGE_DETAIL, '订单详情');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['lookVoucherOrderDetailFields',
						'lookVoucherOrderDetailForm', 'lookVoucherOrderDetailGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/voucher/voucherOrderDetail.js'], function() {
				Ext.getCmp("centerTabPanel").getActiveTab().add(
						lookVoucherOrderDetailSearch(id), orderDetailGrid(id));
				Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
			});
}


/**
 * 批量修改订单状态
 */
function batchOrderUpdateStatus(orderStatus, statusName) {
	var d = Ext.getCmp("voucherOrderConfirmingManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择要确认的订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					var orderIds = "";
					var m = 0;
					for (var i = 0; i < jsonrecord.length; i++) {
						var tmp = jsonrecord[i];
						if (m > 0) {
							orderIds = orderIds + "," + tmp.data.id;
						} else {
							orderIds = tmp.data.id;
						}
						m++;
					}
					commonOrderUpateOrder(orderIds, orderStatus, statusName);
				}
			});
}

/**
 * 订单单个确认
 * 
 * @param {}
 *            orderId
 * @param {}
 *            orderStatus
 * @param {}
 *            statusName
 */
function updateVoucherOrderStatusOne(orderId, orderStatus, statusName) {
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					commonOrderUpateOrder(orderId, orderStatus, statusName);
				}
			});
}

var voucherOrderConfirmingMask = new Ext.LoadMask(Ext.getBody(), {
			msg : "正在提交,请稍后..."
		});
/**
 * 公用修改订单状态方法
 * 
 * @param {}
 *            orderIds
 * @param {}
 *            orderStatus
 * @param {}
 *            statusName
 */
function commonOrderUpateOrder(orderIds, orderStatus, statusName) {
	voucherOrderConfirmingMask.show();
	Ext.Ajax.request({
				url : __ctxPath + "/voucherManager/updateVoucherOrderStatus",
				params : {
					orderIds : orderIds,
					orderStatus : orderStatus,
					statusName : statusName
				},
				method : "post",
				success : function(response, config) {
					voucherOrderConfirmingMask.hide();
					var jsonData = Ext.util.JSON.decode(response.responseText);
					if (jsonData.success) {
						Ext.MessageBox.show({
									title : "信息提示",
									msg : jsonData.data,
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.INFO
								});
						queryVoucherOrdersConfirming();
					} else {
						Ext.MessageBox.show({
									title : "操作信息",
									msg : jsonData.data,
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.ERROR
								});
					}
				},
				failure : function(response, config) {
					voucherOrderConfirmingMask.hide();
					Ext.MessageBox.show({
								title : "错误提示",
								msg : "服务器请求异常，请稍后再试!",
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.ERROR
							});
				}
			});
}

/**
 * 订单打印
 * 
 * @param {}
 *            orderId
 */
function printOrder(orderId) {
	window.open(__ctxPath + "/voucherManager/printOrder?orderId=" + orderId,
			"_blank");
}


// 添发货图片
function insertVoucherOrderPicture(orderId) {
	try {
		addOrUpdVoucherOrderPicture(orderId, "添加发货图片").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/voucher/voucherOrderPictureForm.js'], function() {
			addOrUpdVoucherOrderPicture(orderId, "添加发货图片").show();
				});
	}
}

Ext.getCmp("centerTabPanel").getActiveTab().add(queryVoucherOrderCheckSearch(),
		voucherOrderConfirmingManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
